<template>
  <div class="product-detail-container">
    <!-- 商品基本信息 -->
    <div class="product-base-container">
      <div class="image-gallery">
        <a-carousel
          v-if="product.images?.length"
          animation-name="fade"
          indicator-type="dot"
          auto-play
          class="main-carousel"
        >
          <a-carousel-item v-for="(img, index) in product.images" :key="index">
            <img :src="img" class="carousel-image" />
          </a-carousel-item>
        </a-carousel>
        <img v-else :src="product.coverImage" class="main-image" />
      </div>

      <div class="product-info">
        <h1 class="product-title">{{ product.title }}</h1>
        <div class="price-container">
          <div class="current-price">
            <span class="price-symbol">¥</span>
            <span class="price-number">{{ product.price?.toFixed(2) }}</span>
          </div>
        </div>

        <a-alert class="stock-alert" :type="stockAlertType">
          {{ stockMessage }}
        </a-alert>

        <div class="quantity-selector">
          <span class="selector-label">购买数量：</span>
          <a-input-number
            v-model="quantity"
            :min="1"
            :max="product.stock"
            class="number-input"
          />
        </div>
        <div style="display: flex">
          <a-button
            class="buy-button"
            type="primary"
            shape="round"
            :disabled="product.stock <= 0"
            @click="handlePurchase2"
          >
            <template #icon>
              <icon-shopping-cart />
            </template>
            {{ product.stock > 0 ? "加入购物车" : "已售罄" }}
          </a-button>

          <a-button
            class="buy-button"
            type="primary"
            shape="round"
            :disabled="product.stock <= 0"
            @click="handlePurchase"
          >
            <template #icon>
              <icon-shopping-cart />
            </template>
            {{ product.stock > 0 ? "立即购买" : "已售罄" }}
          </a-button>
        </div>
      </div>
    </div>

    <!-- 用户评价 -->
    <div class="comment-section">
      <h2 class="section-title">用户评价</h2>

      <!-- 评论表单 -->
      <div class="comment-form">
        <a-comment>
          <template #avatar>
            <a-avatar :style="{ backgroundColor: '#00B42A' }">
              {{ currentUser.username?.[0] || "访" }}
            </a-avatar>
          </template>
          <template #content>
            <a-mention
              style="height: 100px"
              v-model="commentContent"
              :placeholder="'写下您的评价...'"
              :rows="3"
            />
            <div class="form-actions">
              <a-space>
                <a-button
                  type="primary"
                  :disabled="!commentContent.trim()"
                  @click="submitComment"
                >
                  发布评价
                </a-button>
                <a-button @click="commentContent = ''">清空</a-button>
              </a-space>
            </div>
          </template>
        </a-comment>
      </div>

      <!-- 评论列表 -->
      <div class="comment-list">
        <a-comment
          v-for="comment in comments"
          :key="comment.commentId"
          class="comment-item"
        >
          <template #avatar>
            <div class="user-avatar">
              <a-avatar
                :size="40"
                :style="{
                  backgroundColor: stringToColor(comment.userName),
                  marginRight: '12px',
                }"
              >
                {{ comment.userName?.[0] }}
              </a-avatar>
            </div>
          </template>

          <template #content>
            <div class="comment-main">
              <!-- 用户信息行 -->
              <div class="user-info-line">
                <span class="username">{{ comment.userName }}</span>
                <a-tag
                  v-if="getUserCookie().role === 1"
                  color="green"
                  size="mini"
                  class="seller-tag"
                >
                  商家
                </a-tag>
                <span class="comment-time">
                  {{ formatTime(comment.createTime) }}
                </span>
              </div>

              <!-- 评论内容 -->
              <div class="comment-content">
                {{ comment.content }}
              </div>
              <!-- 评分 -->
              <div class="rate-line">
                <a-rate
                  :model-value="comment.rating"
                  allow-half
                  readonly
                  :size="16"
                  class="comment-rating"
                />
              </div>
              <div class="action-buttons">
                <a-button
                  type="text"
                  size="mini"
                  @click="handleReply(comment.userId)"
                >
                  <template #icon>
                    <icon-message />
                  </template>
                  回复
                </a-button>
              </div>
            </div>
          </template>
        </a-comment>

        <a-pagination
          v-if="commentTotal > 0"
          :total="commentTotal"
          :page-size="pageSize"
          :current="currentPage"
          @change="handlePageChange"
          class="pagination"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { Message } from "@arco-design/web-vue";
import {
  ProductControllerService,
  CommentControllerService,
  UserControllerService,
  type Comment,
  UserVo,
  OrderControllerService,
} from "@/generated";
import TypeConverter from "@/utils/TypeConverter";
import { getUserCookie, isLogin } from "@/utils/auth";

const route = useRoute();
const router = useRouter();

// 商品数据
const product = ref({
  farmerId: "",
  title: "加载中...",
  price: 0,
  stock: 0,
  coverImage: "",
  description: "",
  category: "",
  viewCount: 0,
  images: [] as string[],
});

// 评论相关
const comments = ref<Comment[]>([]);
const commentTotal = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const commentContent = ref("");

// 当前用户信息
const currentUser = ref<UserVo>({
  username: "",
  role: 0,
});

// 接收传递的商品ID
const productId = TypeConverter.toNumber(route.params["productId"]);

// 购买数量
const quantity = ref(1);

// 库存提示计算属性
const stockAlertType = computed(() => {
  if (product.value.stock <= 0) return "error";
  if (product.value.stock <= 10) return "warning";
  return "info";
});

const stockMessage = computed(() => {
  if (product.value.stock <= 0) return "商品已售罄";
  if (product.value.stock <= 10) return `仅剩 ${product.value.stock} 件`;
  return `库存充足 (${product.value.stock} 件)`;
});

// 加载商品详情
const loadProduct = async () => {
  try {
    const res = await ProductControllerService.getProductById(productId);
    console.log(res);
    if (res.code === 0) {
      product.value = {
        ...res.data,
        images: res.data.images ? JSON.parse(res.data.images) : [],
      };
    }
  } catch (error) {
    Message.error("商品加载失败");
  }
};

// 加载评论
const loadComments = async () => {
  try {
    const res = await CommentControllerService.listComment({
      productId: productId,
    });
    console.log("评价加载成功", res);
    if (res.code === 0) {
      const enrichedComments = await Promise.all(
        res.data.map(async (comment: any) => {
          try {
            const userRes = await UserControllerService.getUserById(
              comment.userId as number
            );
            if (userRes.code === 0) {
              return {
                ...comment,
                userName: userRes.data?.username || "匿名用户",
                role: userRes.data?.role === 1 ? "farmer" : "普通用户",
              };
            }
          } catch (e) {
            console.error("用户信息获取失败", e);
          }
          return comment;
        })
      );

      comments.value = enrichedComments.filter(Boolean);
    }
  } catch (error) {
    Message.error("评价加载失败");
  }
};

// 加载用户信息
const loadUser = async () => {
  try {
    const res = await UserControllerService.getCurrentUser();
    if (res.code === 0) {
      currentUser.value = {
        nickname: res.data.username || "用户",
        isSeller: res.data?.role === 1 ? "farmer" : "普通用户",
      };
    }
  } catch (error) {
    console.log("未登录状态");
  }
};

// 提交评论
const submitComment = async () => {
  try {
    const res = await CommentControllerService.addComment({
      productId: productId,
      content: commentContent.value,
    });
    if (res.code === 0) {
      Message.success("评价成功");
      commentContent.value = "";
      await loadComments();
    }
  } catch (error) {
    Message.error("评价提交失败");
  }
};

const orderId = ref("");

// 购买处理
const handlePurchase = async () => {
  const login = isLogin();
  console.log("是否登录", login);
  if (!login) {
    Message.warning("请先登录");
    await router.push("common/login");
  }
  if (quantity.value <= 0) {
    Message.error("请选择购买数量");
    return;
  }
  if (product.value.stock < quantity.value) {
    Message.error("库存不足");
    return;
  }
  console.log("购买处理", productId, quantity.value);
  const res = await OrderControllerService.createOrder({
    productId: productId,
    quantity: quantity.value,
  });
  console.log("下单结果", res.code == 40100);
  if (res.code === 0) {
    orderId.value = res.data;
    Message.success("下单成功");
    await router.push(`/payment/paymentView/${orderId.value}`);
  } else if (res.code == 40100) {
    await router.push("/common/login");
  }
};

const handlePurchase2 = async () => {
  const login = isLogin();
  console.log("是否登录", login);
  if (!login) {
    Message.warning("请先登录");
    await router.push("/common/login");
  }
  if (quantity.value <= 0) {
    Message.error("请选择购买数量");
    return;
  }
  if (product.value.stock < quantity.value) {
    Message.error("库存不足");
    return;
  }
  console.log("购买处理", productId, quantity.value);
  const res = await OrderControllerService.createOrder({
    productId: productId,
    quantity: quantity.value,
  });
  console.log("下单结果", res.code == 40100);
  if (res.code === 0) {
    Message.success("加入购物车成功");
    if (res.data != null) {
      orderId.value = res.data;
    } else if (res.code == 40100) {
      await router.push("/common/login");
    }
  }
};

/**
 * 回复
 * @param page
 */
const handleReply = async (userId: number) => {
  console.log("回复", userId);
  // 格局id 获取用户信息
  const res = await UserControllerService.getUserById(userId);
  if (res.code === 0) {
    //将用户姓名赋值给评论框
    commentContent.value = `@${res.data?.username} `;
  }
};

// 分页处理
const handlePageChange = (page: number) => {
  currentPage.value = page;
  loadComments();
};

// 工具函数
const formatTime = (time: string) => {
  return new Date(time).toLocaleString();
};

const stringToColor = (str: string) => {
  let hash = 0;
  for (let i = 0; i < str.length; i++) {
    hash = str.charCodeAt(i) + ((hash << 5) - hash);
  }
  const color = `hsl(${hash % 360}, 70%, 50%)`;
  return color;
};

onMounted(async () => {
  await loadUser();
  await loadProduct();
  await loadComments();
});
</script>

<style scoped lang="scss">
.product-detail-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 40px 24px;
  background: #f8fafc;
}

.product-base-container {
  display: grid;
  grid-template-columns: 1.2fr 1fr;
  gap: 32px;
  margin-bottom: 48px;
  background: white;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.06);

  @media (max-width: 768px) {
    grid-template-columns: 1fr;
    gap: 24px;
  }
}

.image-gallery {
  .carousel-image,
  .main-image {
    width: 500px;
    height: 300px;
    object-fit: contain;
  }
}

.product-info {
  .product-title {
    font-size: 28px;
    font-weight: 600;
    color: #1e293b;
    margin-bottom: 24px;
    line-height: 1.3;
  }

  .meta-section {
    display: flex;
    align-items: center;
    gap: 16px;
    margin-bottom: 24px;

    .category-tag {
      padding: 8px 16px;
      font-size: 14px;
      border-radius: 8px;
    }

    .view-count {
      display: flex;
      align-items: center;
      gap: 8px;
      color: #64748b;
      font-size: 14px;
    }
  }

  .price-container {
    margin-bottom: 24px;

    .current-price {
      display: flex;
      align-items: baseline;
      gap: 8px;
      color: #ef4444;

      .price-symbol {
        font-size: 24px;
        font-weight: 500;
      }

      .price-number {
        font-size: 36px;
        font-weight: 700;
      }
    }
  }

  .stock-alert {
    margin-bottom: 24px;
    border-radius: 8px;
  }

  .quantity-selector {
    display: flex;
    align-items: center;
    gap: 16px;
    margin-bottom: 24px;

    .selector-label {
      font-size: 16px;
      color: #475569;
    }

    :deep(.arco-input-number) {
      width: 140px;
      border-radius: 8px;
    }
  }

  .buy-button {
    height: 40px;
    font-size: 16px;
    font-weight: 400;
    border-radius: 12px;
    margin-top: 20px;
    margin-left: 100px;
  }
}

.comment-section {
  .comment-item {
    padding: 16px 0;
    border-bottom: 1px solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }

    :deep(.arco-comment-content) {
      padding: 0;
    }
  }

  .comment-form {
    margin-bottom: 32px;
    padding: 24px;
    background: #f8fafc;
    border-radius: 12px;

    .form-actions {
      margin-top: 16px;
      display: flex;
      justify-content: flex-end;
    }
  }

  .comment-item {
    padding: 16px 0;
    border-bottom: 1px solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }

    :deep(.arco-comment-content) {
      padding: 0;
    }
  }

  .user-avatar {
    margin-right: 12px;
  }

  .comment-main {
    margin-left: 0;
    padding-left: 12px;
  }

  .user-info-line {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 8px;

    .username {
      font-size: 14px;
      color: #333;
      font-weight: 500;
    }

    .seller-tag {
      transform: scale(0.8);
    }

    .comment-time {
      font-size: 12px;
      color: #999;
    }
  }

  .rate-line {
    margin: 8px 0;
    text-align: left;

    :deep(.arco-rate-character) {
      font-size: 16px;
      color: #ffb400;
      margin-right: 2px;
    }
  }

  .comment-content {
    /*靠左显示*/
    text-align: left;
    font-size: 14px;
    color: #333;
    line-height: 1.6;
    margin: 8px 0;
  }

  .action-buttons {
    margin-top: 12px;
    display: flex;
    gap: 16px;
    justify-content: flex-end;

    .arco-btn {
      padding: 0 8px;
      height: 24px;
      font-size: 12px;
      color: #666;

      &:hover {
        background: #f5f5f5;
      }
    }
  }

  .pagination {
    margin-top: 32px;
    display: flex;
    justify-content: center;
  }
}

@media (max-width: 768px) {
  .user-info-line {
    flex-wrap: wrap;
    gap: 4px;
  }

  .comment-main {
    padding-left: 8px;
  }
}
</style>
